package com.sunb2b.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sunb2b.entity.Region;
import com.sunb2b.service.RegionService;
import com.sunb2b.service.Staticizer;
import com.sunb2b.util.JsonUtils;

import freemarker.template.TemplateException;

@Controller

public class RegionController {
    
    @Inject
    private RegionService regionService;
    
    @RequestMapping(value="/regionUtil")
    public String getAllRegions(Model model) {
        Map jsonMap = new HashMap();
        List<Region> regions = regionService.getAllRegions();
        for(Region r : regions){
            jsonMap.put(r.getId(), r.getName());
        }
        String json = JsonUtils.map2json(jsonMap);
        model.addAttribute("regionsJson", json);
        return "RegionUtil";
    }
    
    public void staticize(Staticizer staticizer, String currentPath) 
    			throws IOException, TemplateException{
    	Map jsonMap = new HashMap();
        List<Region> regions = regionService.getAllRegions();
        for(Region r : regions){
            jsonMap.put(r.getId(), r.getName());
        }
        String json = JsonUtils.map2json(jsonMap);
        
    	Map data = new HashMap();
        data.put("regionsJson", json);
        Map env = new HashMap();
        env.put("data", data);
        env.put("tpl", "regionUtil.ftl");
        env.put("outputFileName", currentPath + "/resources/scripts/regionUtil.js");
        staticizer.process(env);
    }
    
    @RequestMapping(value="/admin/region/staticize")
    public String staticize(HttpServletRequest request, Model model) 
    			throws IOException, TemplateException {
    	String currentPath = request.getSession().getServletContext().getRealPath("/");
    	System.out.println(currentPath);
        Staticizer staticizer = new Staticizer(currentPath + "/tpl");
        staticize(staticizer, currentPath);
        String message = "Operation was done successfully.";
        model.addAttribute("message", message);
        //model.addAttribute("regionsJson", json);
        return "admin/region/staticize";
    }
    @RequestMapping(value="/admin/region/preStaticize")
    public String preStaticize(){
    	return "admin/region/staticize";
    }
}
